/**
 * 数据源详情页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Descriptions,
  Button,
  Space,
  message,
  Tabs,
  Table,
  Tag,
  Modal,
  Form,
  Input,
  Switch,
  Tooltip,
  Alert,
} from 'antd';
import {
  ArrowLeftOutlined,
  EditOutlined,
  ApiOutlined,
  EyeOutlined,
  ReloadOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';
import { getDataSource, type DataSourceItem } from '@/services/dataSource';
import {
  analyzeDataSourceFields,
  getDataSourceFields,
  updateDataSourceField,
  previewDataSourceData,
  type DataSourceField,
  type DataSourceFieldUpdate,
  type DataSourceDataPreview,
  getFieldTypeLabel,
  FieldType,
} from '@/services/dataSourceField';
import DataSourcePreview from '@/components/DataSourcePreview';
import DataSourceFieldManager from '@/components/DataSourceFieldManager';

const { TabPane } = Tabs;

const DataSourceDetail: React.FC = () => {
  const params = useParams();
  const dataSourceId = parseInt(params.id as string);
  
  const [loading, setLoading] = useState(true);
  const [fieldsLoading, setFieldsLoading] = useState(false);
  const [previewLoading, setPreviewLoading] = useState(false);
  const [dataSource, setDataSource] = useState<DataSourceItem | null>(null);
  const [fields, setFields] = useState<DataSourceField[]>([]);
  const [previewData, setPreviewData] = useState<DataSourceDataPreview | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectedField, setSelectedField] = useState<DataSourceField | null>(null);
  const [form] = Form.useForm();

  // 获取数据源详情
  const fetchDataSource = async () => {
    try {
      const data = await getDataSource(dataSourceId);
      setDataSource(data);
    } catch (error: any) {
      message.error(error.message || '获取数据源详情失败');
      history.push('/datasources');
    } finally {
      setLoading(false);
    }
  };

  // 分析数据源字段
  const handleAnalyzeFields = async () => {
    setFieldsLoading(true);
    try {
      const analysis = await analyzeDataSourceFields(dataSourceId);
      setFields(analysis.fields);
      message.success(`分析完成，共发现 ${analysis.total_fields} 个字段`);
    } catch (error: any) {
      message.error(error.message || '分析字段失败');
    } finally {
      setFieldsLoading(false);
    }
  };

  // 获取字段列表
  const fetchFields = async () => {
    setFieldsLoading(true);
    try {
      const fieldList = await getDataSourceFields(dataSourceId);
      setFields(fieldList);
    } catch (error: any) {
      message.error(error.message || '获取字段列表失败');
    } finally {
      setFieldsLoading(false);
    }
  };

  // 预览数据
  const handlePreviewData = async () => {
    setPreviewLoading(true);
    try {
      const preview = await previewDataSourceData(dataSourceId, 20);
      setPreviewData(preview);
    } catch (error: any) {
      message.error(error.message || '预览数据失败');
    } finally {
      setPreviewLoading(false);
    }
  };

  // 编辑字段
  const handleEditField = (field: DataSourceField) => {
    setSelectedField(field);
    form.setFieldsValue({
      display_name: field.display_name,
      description: field.description,
      is_email: field.is_email,
      is_name: field.is_name,
      sample_value: field.sample_value,
      data_format: field.data_format,
    });
    setEditModalVisible(true);
  };

  // 保存字段编辑
  const handleSaveField = async (values: DataSourceFieldUpdate) => {
    if (!selectedField) return;

    try {
      const updatedField = await updateDataSourceField(selectedField.id, values);
      setFields(fields.map(f => f.id === updatedField.id ? updatedField : f));
      message.success('字段更新成功');
      setEditModalVisible(false);
      form.resetFields();
    } catch (error: any) {
      message.error(error.message || '字段更新失败');
    }
  };

  useEffect(() => {
    if (dataSourceId) {
      fetchDataSource();
      fetchFields();
    }
  }, [dataSourceId]);

  // 获取字段类型标签
  const getFieldTypeTag = (fieldType: FieldType) => {
    const colorMap: Record<FieldType, string> = {
      [FieldType.TEXT]: 'default',
      [FieldType.NUMBER]: 'blue',
      [FieldType.EMAIL]: 'green',
      [FieldType.DATE]: 'orange',
      [FieldType.DATETIME]: 'orange',
      [FieldType.BOOLEAN]: 'purple',
      [FieldType.JSON]: 'cyan',
      [FieldType.LONGTEXT]: 'default',
      [FieldType.URL]: 'geekblue',
      [FieldType.PHONE]: 'volcano',
      [FieldType.CURRENCY]: 'gold',
    };
    
    return (
      <Tag color={colorMap[fieldType] || 'default'}>
        {getFieldTypeLabel(fieldType)}
      </Tag>
    );
  };

  // 字段表格列定义
  const fieldColumns: ColumnsType<DataSourceField> = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: DataSourceField) => (
        <div>
          <div style={{ fontWeight: 500 }}>{text}</div>
          {record.display_name && record.display_name !== text && (
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.display_name}
            </div>
          )}
        </div>
      ),
    },
    {
      title: '类型',
      dataIndex: 'field_type',
      key: 'field_type',
      render: (fieldType: FieldType) => getFieldTypeTag(fieldType),
    },
    {
      title: '属性',
      key: 'properties',
      render: (_, record: DataSourceField) => (
        <Space wrap>
          {record.is_primary && <Tag color="red">主键</Tag>}
          {record.is_email && <Tag color="green">邮箱</Tag>}
          {record.is_name && <Tag color="blue">姓名</Tag>}
          {!record.is_nullable && <Tag color="orange">必填</Tag>}
        </Space>
      ),
    },
    {
      title: '样例值',
      dataIndex: 'sample_value',
      key: 'sample_value',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: DataSourceField) => (
        <Button
          type="text"
          icon={<EditOutlined />}
          onClick={() => handleEditField(record)}
        >
          编辑
        </Button>
      ),
    },
  ];

  // 数据预览表格列定义
  const getPreviewColumns = (): ColumnsType<any> => {
    if (!previewData || previewData.fields.length === 0) return [];
    
    return previewData.fields.map(field => ({
      title: field.display_name || field.name,
      dataIndex: field.name,
      key: field.name,
      ellipsis: true,
      render: (text: any) => {
        if (text === null || text === undefined) return '-';
        if (typeof text === 'object') return JSON.stringify(text);
        return String(text);
      },
    }));
  };

  if (loading) {
    return (
      <PageContainer>
        <Card loading />
      </PageContainer>
    );
  }

  if (!dataSource) {
    return (
      <PageContainer>
        <Card>
          <Alert message="数据源不存在" type="error" />
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: `数据源详情 - ${dataSource.name}`,
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="edit"
          icon={<EditOutlined />}
          onClick={() => history.push(`/datasources/edit/${dataSourceId}`)}
        >
          编辑数据源
        </Button>,
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/datasources')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Card>
        <Tabs defaultActiveKey="info">
          <TabPane tab="基本信息" key="info">
            <Descriptions column={2} bordered>
              <Descriptions.Item label="数据源名称">{dataSource.name}</Descriptions.Item>
              <Descriptions.Item label="数据源类型">
                <Tag color="blue">{dataSource.type.toUpperCase()}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">
                {new Date(dataSource.created_at).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="更新时间">
                {new Date(dataSource.updated_at).toLocaleString()}
              </Descriptions.Item>
              {dataSource.type === 'mysql' && (
                <>
                  <Descriptions.Item label="数据库主机">
                    {dataSource.config.host}:{dataSource.config.port}
                  </Descriptions.Item>
                  <Descriptions.Item label="数据库名称">
                    {dataSource.config.database}
                  </Descriptions.Item>
                  <Descriptions.Item label="用户名">
                    {dataSource.config.username}
                  </Descriptions.Item>
                  {dataSource.config.table_name && (
                    <Descriptions.Item label="表名">
                      {dataSource.config.table_name}
                    </Descriptions.Item>
                  )}
                </>
              )}
              {(dataSource.type === 'csv' || dataSource.type === 'excel') && (
                <>
                  <Descriptions.Item label="文件路径" span={2}>
                    {dataSource.config.file_path}
                  </Descriptions.Item>
                  {dataSource.type === 'excel' && dataSource.config.sheet_name && (
                    <Descriptions.Item label="工作表名称">
                      {dataSource.config.sheet_name}
                    </Descriptions.Item>
                  )}
                </>
              )}
            </Descriptions>
          </TabPane>

          <TabPane tab="字段管理" key="fields">
            <DataSourceFieldManager
              dataSourceId={dataSourceId}
              dataSourceType={dataSource?.type || ''}
            />
          </TabPane>

          <TabPane tab="数据预览" key="preview">
            <DataSourcePreview
              dataSourceId={dataSourceId}
              dataSourceType={dataSource?.type || ''}
            />
          </TabPane>
        </Tabs>
      </Card>

      {/* 编辑字段弹窗 */}
      <Modal
        title={`编辑字段 - ${selectedField?.name}`}
        open={editModalVisible}
        onCancel={() => {
          setEditModalVisible(false);
          form.resetFields();
        }}
        footer={null}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSaveField}
        >
          <Form.Item name="display_name" label="显示名称">
            <Input placeholder="请输入字段显示名称" />
          </Form.Item>

          <Form.Item name="description" label="字段描述">
            <Input.TextArea rows={3} placeholder="请输入字段描述" />
          </Form.Item>

          <Form.Item name="sample_value" label="样例值">
            <Input placeholder="请输入样例值" />
          </Form.Item>

          <Form.Item name="data_format" label="数据格式">
            <Input placeholder="请输入数据格式说明" />
          </Form.Item>

          <Form.Item name="is_email" label="邮箱字段" valuePropName="checked">
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>

          <Form.Item name="is_name" label="姓名字段" valuePropName="checked">
            <Switch checkedChildren="是" unCheckedChildren="否" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                保存
              </Button>
              <Button onClick={() => setEditModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default DataSourceDetail;
